package com.senlingspace.system.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.utils.DateUtils;
import com.senlingspace.common.utils.NumberGenerator;
import com.senlingspace.common.utils.PageUtils;
import com.senlingspace.system.domain.SlkjFareSchemeDetail;
import com.senlingspace.system.domain.SlkjTicketLevel;
import com.senlingspace.system.domain.vo.SlkjTicketCategoryVo;
import com.senlingspace.system.event.ActionEvent;
import com.senlingspace.system.mapper.SlkjFareSchemeDetailMapper;
import com.senlingspace.system.mapper.SlkjTicketLevelMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.senlingspace.system.mapper.SlkjTicketCategoryMapper;
import com.senlingspace.system.domain.SlkjTicketCategory;
import com.senlingspace.system.service.ISlkjTicketCategoryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 票类管理Service业务层处理
 *
 * @author SenlingSpace
 * @date 2024-07-03
 */
@Service
public class SlkjTicketCategoryServiceImpl implements ISlkjTicketCategoryService {
    @Autowired
    private SlkjTicketCategoryMapper slkjTicketCategoryMapper;
    @Autowired
    private SlkjTicketLevelMapper slkjTicketLevelMapper;
    @Autowired
    private SlkjFareSchemeDetailMapper slkjFareSchemeDetailMapper;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;


    /**
     * 查询票类管理
     *
     * @param id 票类管理主键
     * @return 票类管理
     */
    @Override
    public SlkjTicketCategory selectSlkjTicketCategoryById(Long id) {
        return slkjTicketCategoryMapper.selectSlkjTicketCategoryById(id);
    }

    /**
     * 查询票类管理列表
     *
     * @param slkjTicketCategory 票类管理
     * @param paginate           是否需要分页
     * @return 票类管理
     */
    @Override
    public PageInfo<SlkjTicketCategoryVo> selectSlkjTicketCategoryList(SlkjTicketCategory slkjTicketCategory, boolean paginate) {
        Page<Object> page = PageUtils.startPageExt(paginate);
        List<SlkjTicketCategoryVo> ticketCategories = slkjTicketCategoryMapper.selectSlkjTicketCategoryListExt(slkjTicketCategory);
        if (CollectionUtils.isEmpty(ticketCategories)) {
            return new PageInfo<>(Lists.newArrayList());
        }
        long total = page.getTotal();

        List<SlkjTicketLevel> ticketLevels = slkjTicketLevelMapper.selectSlkjTicketLevelList(null);
        Map<Long, SlkjTicketLevel> ticketLevelMap = ticketLevels.stream().collect(Collectors.toMap(SlkjTicketLevel::getId, level -> level));

        for (SlkjTicketCategoryVo ticketCategory : ticketCategories) {
            ticketCategory.setTicketLevelName(ticketLevelMap.get(ticketCategory.getTicketLevelId()).getName());
        }

        PageInfo<SlkjTicketCategoryVo> pageInfo = new PageInfo<>(ticketCategories);
        pageInfo.setTotal(total);
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        return pageInfo;
    }

    /**
     * 新增票类管理
     *
     * @param slkjTicketCategory 票类管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSlkjTicketCategory(SlkjTicketCategory slkjTicketCategory) {
        slkjTicketCategory.setNumber(NumberGenerator.getCharacters());
        slkjTicketCategory.setCreateTime(DateUtils.getNowDate());
        int inserted = slkjTicketCategoryMapper.insertSlkjTicketCategory(slkjTicketCategory);

        if (inserted > 0) {
            applicationEventPublisher.publishEvent(ActionEvent.of(slkjTicketCategory, "同步票价方案"));
        }
        return inserted;
    }


    /**
     * 修改票类管理
     *
     * @param slkjTicketCategory 票类管理
     * @return 结果
     */
    @Override
    public int updateSlkjTicketCategory(SlkjTicketCategory slkjTicketCategory) {
        slkjTicketCategory.setUpdateTime(DateUtils.getNowDate());
        return slkjTicketCategoryMapper.updateSlkjTicketCategory(slkjTicketCategory);
    }

    /**
     * 批量删除票类管理
     *
     * @param ids    需要删除的票类管理主键
     * @param userId 操作人ID
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult deleteSlkjTicketCategoryByIds(Long[] ids, Long userId) {
        List<SlkjFareSchemeDetail> fareSchemeDetails = slkjFareSchemeDetailMapper.selectSlkjFareSchemeDetailByTicketCategoryIds(ids);
        if (CollectionUtils.isEmpty(fareSchemeDetails)) {
            slkjTicketCategoryMapper.updateSlkjTicketCategoryStatusByIds(ids, userId);
            return AjaxResult.success("删除成功！");
        }

        SlkjFareSchemeDetail fareSchemeDetail = fareSchemeDetails.get(0);
        boolean could = canDeleteFareScheme(fareSchemeDetail);
        if (could) {
            slkjTicketCategoryMapper.updateSlkjTicketCategoryStatusByIds(new Long[]{fareSchemeDetail.getTicketCategoryId()}, userId);
            slkjFareSchemeDetailMapper.updateSlkjFareSchemeDetailStatusByCategoryId(fareSchemeDetail.getTicketCategoryId(), fareSchemeDetail.getTicketLevelId());
            return AjaxResult.success("删除成功！");
        }

        return AjaxResult.error("票类已被关联使用，禁止删除！");
    }

    public boolean canDeleteFareScheme(SlkjFareSchemeDetail detail) {
        // 检查所有价格字段是否都为null
        if (detail.getShopPrice() != null ||
                detail.getMiniProgramPrice() != null ||
                detail.getDouyinPrice() != null ||
                detail.getOriginalPrice() != null) {
            // 如果任意一个字段不为null，则不能删除
            return false;
        }
        // 如果所有记录的所有价格字段都为null，则可以删除
        return true;
    }

    /**
     * 删除票类管理信息
     *
     * @param id 票类管理主键
     * @return 结果
     */
    @Override
    public int deleteSlkjTicketCategoryById(Long id) {
        return slkjTicketCategoryMapper.deleteSlkjTicketCategoryById(id);
    }

    @Override
    public List<SlkjTicketCategory> selectSlkjTicketCategoryByIds(List<Long> categoryIds) {
        return slkjTicketCategoryMapper.selectSlkjTicketCategoryByIds(categoryIds);
    }

}
